package com.ruoyi.accounts.aop;

import com.ruoyi.accounts.tcp.TcpUsersStruct;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.net.Socket;

@Aspect
@Component
@Slf4j
public class SocketConnectionCheckAspect {

    @Pointcut("@annotation(com.ruoyi.accounts.aop.CheckSocketConnection)")
    public void checkSocketConnectionPointcut() {
    }

    @Before("checkSocketConnectionPointcut()")
    public void checkConnectionBefore(JoinPoint joinPoint) {
        log.debug("AOP Check: Entering checkConnectionBefore for method: {}", joinPoint.getSignature().toShortString());

        Object[] args = joinPoint.getArgs();

        if (args == null || args.length < 2 || !(args[1] instanceof String)) {
            log.error("AOP Check Failed: Method {} annotated with @CheckSocketConnection does not have a String as the second argument for machine ID.", joinPoint.getSignature().toShortString());
            throw new IllegalArgumentException("Invalid method signature for @CheckSocketConnection");
        }

        String machineId = (String) args[1];
        log.debug("AOP Check: Checking connection for machine ID: {}", machineId);

        Socket clientSocket = TcpUsersStruct.get(machineId);

        if (clientSocket == null) {
            log.warn("AOP Check Failed: Socket not found for machine ID: {}", machineId);
            throw new RuntimeException("目标机器 " + machineId + " 未连接或未找到");
        }

        if (clientSocket.isClosed()) {
            log.warn("AOP Check Failed: Socket is closed for machine ID: {}. Remote Address: {}", machineId, clientSocket.getRemoteSocketAddress());
            throw new RuntimeException("目标机器 " + machineId + " 连接已关闭");
        }

        log.debug("AOP Check Passed: Socket found and is not closed for machine ID: {}", machineId);
    }
}
